// miniprogram/pages/user-center/userinfo/userinfo.js
const app = getApp();
const request = require('../../../utils/request.js')
const config = require('../../../utils/config.js');
const util = require('../../../utils/util.js');

const TIME_CODE = 60;
var interval = null;   //倒计时函数

Page({
  data: {
    colorTheme: app.globalData.colorTheme,
    userInfo: {},
    experiences: {},
    editName: null,
    sex: ['保密', '男', '女'],
    checkbox: [],
    choosedTags: [],
    emailInput: '',
    emailCode: '',
    codeStatus: true,
    currentTime: TIME_CODE
  },

  /**
   * 生命周期函数--监听页面显示
   */ 
  onShow: function (e) {
    let url = config.SERVER_URL + 'user/showSelfPage';
    let that = this;
    // 获取本地缓存的token
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载ing...'
    });
    // 请求获取用户信息
    request.requestGetApi(url, token, {}, "application/json").then(res => {
      if (res.status === config.STATUS_OK) {
        let userInfo = res.data;
        wx.setStorageSync('userInfo', userInfo);
        this.setData({
          userInfo: userInfo
        })
      }
    }).catch(err => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 保存用户经历
   */
  saveExperiences: function (e) {
    let params = e.detail.value;
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'user/saveUserExperiences';
    wx.showLoading({
      title: '保存ing...'
    });
    request.requestPostApi(url, token, params, 'application/json').then(res => {
      if (res.status != config.STATUS_OK) {
        app.failFun(res);
        return;
      }
      this.onShow();
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    }).catch(err => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res)
    })
    this.hideModal();
  },

  /**
   * 保存用户性别
   */
  sexPickerChange: function (e) {
    let e2 = {
      detail: {
        value: {
          sex: e.detail.value
        }
      }
    };
    console.log(e2.detail.value);
    this.saveUserSimpleInfo(e2);
  },

  /**
   * 保存昵称、个人描述、性别
   */
  saveUserSimpleInfo: function (e) {
    let param = e.detail.value;
    console.log(param);
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'user/updateUserSimpleInfo';
    wx.showLoading({
      title: '保存ing'
    })
    request.requestPostApi(url, token, param, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        this.onShow();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
        // 关闭编辑状态
        this.hideEdit()
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 图片放大
   */
  preview: function (e) {
    let imageUrl = e.currentTarget.dataset.imageurl;
    wx.previewImage({
      current: imageUrl, // 当前显示图片的http链接
      urls: [imageUrl] // 需要预览的图片http链接列表
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();

    wx.stopPullDownRefresh();
  },

  /**
   * 模态框
   */
  showModal (e) {
    let modalName = e.currentTarget.dataset.target;
    if (modalName == 'Image') {
      this.setData({
        imageUrl: e.currentTarget.dataset.imageurl
      });
    }
    this.setData({
      modalName: modalName
    })
  },
  hideModal (e) {
    this.setData({
      modalName: null,
      experiences: {}
    })
  },

  /**
   * 服务器获取标签
   */
  showTagsModal: function (e) {
    let that = this;
    let url = config.SERVER_URL + 'tags/listAllTags'
    wx.showLoading({
      title: '加载ing...'
    })
    request.requestGetApi(url, {}, {}, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        let allTags = res.data;
        let userTags = wx.getStorageSync('userInfo').tags;
        for (let i = 0; i < userTags.length; i++) {
          allTags.find(function (value, index) {
            if (value.id == userTags[i].id) {
              allTags[index]['checked'] = true;
            }
          });
        }
        let choosedTags = [];
        for (let i = 0; i < userTags.length; i++) {
          choosedTags.push(userTags[i].id);
        }
        this.setData({
          checkbox: allTags,
          choosedTags: choosedTags
        });
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
    this.showModal(e);
  },

  /**
   * 编辑框
   */
  showEdit (e) {
    if (this.data.editName == 'wait') {
      this.data.editName = null;
      return;
    }
    this.setData({
      editName: e.currentTarget.dataset.target
    });
  },
  hideEdit (e) {
    this.setData({
      editName: 'wait'
    })
  },

  /**
   * 监听邮箱文本框输入事件
   */
  changeEmail: function(e){
    this.data.emailInput = e.detail.value;
  },

  /**
   * 验证码重发倒计时
   */
  doLoop: function(){
    let currentTime = this.data.currentTime;
    interval = setInterval(() => {
      this.setData({
        currentTime: --currentTime
      });
      if(currentTime <= 0){
        clearInterval(interval);
        this.setData({
          codeStatus: true,
          currentTime: TIME_CODE
        })
      }
    }, 1000);
  },

  /**
   * 获取邮箱验证码
   */
  getEmailCode: function () {
    let email = this.data.emailInput;
    if(!email || !util.checkEmail(email)){
      wx.showToast({
        title: email ? '请输入合法邮箱！' : '邮箱不能为空！',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    let url = config.SERVER_URL + 'user/sendEmailCode?email=' + email;
    let token = wx.getStorageSync('token');
    request.requestPostApi(url, token, {}, 'application/json').then((res)=>{
      if (res.status === config.STATUS_OK) {
        this.setData({
          codeStatus: false
        });
        this.doLoop();
      }
    }).catch(err => {
      app.failFun(err)
    });
  },

  /**
   * 提交邮箱
   */
  submitEmail: function (e) {
    let params = e.detail.value;
    let msg = this.checkForm(params);
    if(msg){
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 1500
      });
      return;
    }
    let url = config.SERVER_URL + 'user/bindEmail?code=' + params.code + '&email=' + params.email;
    let token = wx.getStorageSync('token');
    request.requestPostApi(url, token, {}, 'application/json').then((res)=>{
      if (res.status === config.STATUS_OK) {
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 2000
        });
        let userInfo = this.data.userInfo;
        userInfo.email = params.email;
        this.setData({
          emailInput: '',
          emailCode: '',
          userInfo
        });
        this.hideModal();
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 1500
        });
      }
    }).catch(err => {
      app.failFun(err)
    });
  },

  /**
   * 校验文本框是否为空
   */
  checkForm: function (params) {
    console.log(params);
    if (!params.email){
      return '邮箱不能为空！';
    }
    if (!params.code) {
      return '验证码不能为空！';
    }
  },

  /**
   * 打开项目经历详情的模态框，并填充数据
   */
  updateExperiences: function (e) {
    let index = e.currentTarget.dataset.target;
    console.log(this.data.userInfo.experiences[index]);
    this.setData({
      experiences: this.data.userInfo.experiences[index],
      modalName: 'experiencesModel'
    });
  },
  /**
   * 删除用户经历
   */
  deleteExperiences: function (e) {
    let id = e.currentTarget.dataset.target;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'user/deleteUserExperiences?id=' + id;
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗',
      success (res) {
        if (res.confirm) {
          request.requestPostApi(url, token, {}, 'application/json').then(res => {
            if (res.status === config.STATUS_OK) {
              that.onShow();
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
            }
          }).catch(err => {
            app.failFun(err)
          }).finally((res) => {
            app.completeFun(res)
          })
          wx.showLoading({
            title: '删除ing...'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
      complete (res) {
        wx.hideLoading();
      }
    })
  },

  /**
   * 点中标签
   */
  chooseTag: function (e) {
    let id = e.currentTarget.dataset.value;
    let allTags = this.data.checkbox;
    let choosedTags = [];
    allTags.find(function (value, index) {
      if (id == value.id) {
        allTags[index].checked = !allTags[index].checked;
      }
      if (allTags[index].checked == true) {
        choosedTags.push(allTags[index].id)
      }
    });
    if (choosedTags.length > 3) {
      wx.showModal({
        title: '提示',
        content: '标签数量不能 > 3',
      })
    }
    console.log(choosedTags);
    this.setData({
      checkbox: allTags,
      choosedTags: choosedTags
    })
  },

  /**
   * 保存标签
   */
  saveUserTags: function (e) {
    let that = this;
    let choosedTags = this.data.choosedTags;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'user/saveUserTags';
    wx.showLoading({
      title: '保存ing...'
    });
    request.requestPostApi(url, token, choosedTags, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        this.hideModal();
        this.onShow();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      } else{
        wx.showModal({
          title: '提示',
          content: '标签数量不能 > 3',
        })
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
  },

  /**
   * 更新头像
   */
  updateAvatar: function (e) {
    let token = wx.getStorageSync('token');
    let that = this;
    wx.chooseImage({
      success (res) {
        const tempFilePaths = res.tempFilePaths
        wx.showLoading({
          title: '上传ing'
        });
        wx.uploadFile({
          url: config.SERVER_URL + 'user/updateUserAvatar', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'avatar',
          header: {
            'UT-Token': token
          },
          success (res) {
            if (res.statusCode != config.STATUS_OK) {
              app.failFun(res, that);
            }
            that.onShow();
            wx.hideLoading();
            wx.showToast({
              title: '头像更新成功'
            });
          }
        })
      }
    })
  },

  // ListTouch触摸开始
  ListTouchStart (e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove (e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd (e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

  // 按钮动画事件
  toggle(e) {
    var anmiaton = 'shake';
    var that = this;
    that.setData({
      animation: anmiaton
    })
    setTimeout(function() {
      that.setData({
        animation: ''
      })
    }, 1000)
  }
})